﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Data.OleDb;

/// <summary>
/// common 的摘要说明
/// </summary>
public class common
{
	public common()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//

      
	}

/// <summary>
        /// 读取DataSet中的数据到字符串中
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static string ExportTable(DataSet ds, string[] columnName)
        {
            StringBuilder sb = new StringBuilder();
            //data = ds.DataSetName + "\n"; 
            int count = 0;

            foreach (DataTable tb in ds.Tables)
            {
                //data += tb.TableName + "\n"; 
                sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">");
                sb.AppendLine("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
                //写出列名 
                sb.AppendLine("<tr style=\"font-weight: bold; white-space: nowrap;\">");

                if (columnName == null)
                {
                    foreach (DataColumn column in tb.Columns)
                    {
                        sb.AppendLine("<td>" + SqlHelper.ToChgHTMLString(Convert.ToString(column.ColumnName)) + "</td>");
                    }
                }
                else
                {
                    foreach (string column in columnName)
                    {
                        sb.AppendLine("<td>" + SqlHelper.ToChgHTMLString(Convert.ToString(column)) + "</td>");
                    }
                }
                sb.AppendLine("</tr>");

                //写出数据 
                foreach (DataRow row in tb.Rows)
                {
                    sb.Append("<tr>");
                    foreach (DataColumn column in tb.Columns)
                    {
                        // 如果是int的需要转换格式 
                        //if (column.ColumnName.Equals("mobile") || column.ColumnName.Equals("mobile"))
                        //    sb.Append("<td style=\"vnd.ms-excel.numberformat:@\">" + row[column].ToString() + "</td>");
                        //else
                        sb.Append("<td>" + SqlHelper.ToChgHTMLString(Convert.ToString(row[column].ToString())) + "</td>");

                    }
                    sb.AppendLine("</tr>");
                    count++;
                }
                sb.AppendLine("</table>");
            }

            return sb.ToString();
        }

        /// <summary>
        /// 导出DS到Excel文件中
        /// </summary>
        /// <param name="page"> 当前页的Page</param>
        /// <param name="fileName">文件的前缀名，如：Store，不需要加入.xls及唯一性，会自动生成。如果用DataSet默认的，直接赋值null</param>
        /// <param name="ds">目标数据集</param>
        public static void ExportDsToXls(Page page, string fileName, DataSet ds, string[] columnName)
        {

            page.Response.Clear();
            page.Response.Buffer = true;
            page.Response.Charset = "GB2312";
            //page.Response.Charset = "UTF-8";
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + System.DateTime.Now.ToString("_yyMMdd_hhmm") + ".xls");
            page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
            page.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
            page.EnableViewState = false;
            page.Response.Write(ExportTable(ds, columnName));
            page.Response.End();

        }


    /// <summary>
    /// 文件上传
    /// </summary>
    /// <param name="fileMiddle">文件路径的中间部分</param>
    /// <param name="fileUploadName">上传的文件名</param>
    /// <param name="str">错误信息</param>
    public static string  FileUpload(string fileMiddle, string fileUploadName, ref string str)
    {
        string filepath = "";
        string path = System.Web.HttpContext.Current.Request.PhysicalApplicationPath.ToString() + fileMiddle;
        string myFileName = "";
        int lastindex = 0;
        //上传图片
        filepath = fileUploadName;
        if (filepath != "")
        {
            lastindex = filepath.LastIndexOf("\\");

            string extenionName = filepath.Substring(filepath.LastIndexOf('.'));
            try
            {
                myFileName = DateTime.Now.ToFileTime().ToString() + filepath.Substring(lastindex + 1).Trim();
                HttpContext.Current.Request.Files[0].SaveAs(path + myFileName);
            }
            catch
            {
                str = "文件上传失败！";
            }
        }
        else
        {
            str = "请上传文件！";
        }

        return myFileName;
    }


    /// <summary>
    /// 文件上传
    /// </summary>
    /// <param name="fileMiddle">文件路径的中间部分</param>
    /// <param name="fileUploadName">上传的文件名</param>
    /// <param name="str">错误信息</param>
    public static string FileUploadOnline(FileUpload fu, string fileMiddle, string fileUploadName, ref string str)
    {
        string filepath = "";
        string path = System.Web.HttpContext.Current.Request.PhysicalApplicationPath.ToString() + fileMiddle;
        string myFileName = "";
        int lastindex = 0;
        //上传图片
        filepath = fileUploadName;
        if (filepath != "")
        {
            lastindex = filepath.LastIndexOf("\\");

            string extenionName = filepath.Substring(filepath.LastIndexOf('.'));
            try
            {
                myFileName = DateTime.Now.ToFileTime().ToString() + filepath.Substring(lastindex + 1).Trim();
               fu.SaveAs(path + myFileName);
            }
            catch
            {
                str = "文件上传失败！";
            }
        }
        else
        {
            str = "请上传文件！";
        }

        return myFileName;
    }





    /// <summary>
    /// 文件上传
    /// </summary>
    /// <param name="fileMiddle">文件路径的中间部分</param>
    /// <param name="fileUploadName">上传的文件名</param>
    /// <param name="str">错误信息</param>
    public static string FileUploadPic(string fileMiddle, string fileUploadName, ref string str)
    {
        string filepath = "";
        string path = System.Web.HttpContext.Current.Request.PhysicalApplicationPath.ToString() + fileMiddle;
        string myFileName = "";
        int lastindex = 0;
        //上传图片
        filepath = fileUploadName;
        if (filepath != "")
        {
            lastindex = filepath.LastIndexOf("\\");

            string extenionName = filepath.Substring(filepath.LastIndexOf('.'));

            
            try
            {
                 if (extenionName.ToLower() == ".jpg" || extenionName.ToLower() == ".gif" || extenionName.ToLower() == ".png")
                {
                    myFileName = DateTime.Now.ToFileTime().ToString() + filepath.Substring(lastindex + 1);
                    HttpContext.Current.Request.Files[0].SaveAs(path + myFileName);
                }
                else
                {
                    str = "请上传扩展名为jpg,gif或png的图片!";
                    
                }

            }
            catch
            {
                str = "图片上传失败！";
            }
        }
        else
        {
            str = "请上传图片！";
        }

        return myFileName;
    }



    #region 得到服务器上的Xls填充的DataTable
    /// <summary>
    /// 得到服务器上的Xls填充的DataTable
    /// </summary>
    /// <param name="path">xls在服务器上的绝对路径</param>
    /// <param name="fields">要读取的字段，以,分割，至少要有一个字段</param>
    /// <returns>DataTable，为null读取失败</returns>
    public static DataTable getDataTableSell(string path, string fields, ref string cueInfo)
    {
        //string strConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + _physicalPath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";
        string connStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";
        //= "Provider=Microsoft.Jet.OLEDB.4.0;" + "Extended Properties=Excel 8.0;" + "data source=" + path;
        DataTable dtSell = null;
        try
        {
            DataSet dsSell = new DataSet();
            using (OleDbConnection odconn = new OleDbConnection(connStr))
            {
                using (OleDbDataAdapter odda = new OleDbDataAdapter(@"SELECT " + fields + " FROM [Sheet1$]", odconn))
                {
                    odda.Fill(dsSell, "sell");
                    if (dsSell != null && dsSell.Tables.Count > 0)
                    {
                        dtSell = dsSell.Tables[0];
                    }
                }
            }
        }
        catch
        {
            cueInfo += "从Excel读取数据失败!!\r";
        }
        return dtSell;
    }
    #endregion

    #region 解密
    public static string UrlPro(string para, string url)
    {
        string[] splitChar = new string[2];
        splitChar[0] = "?" + para + "=";
        splitChar[1] = "&" + para + "=";

        string id = "0";

        int index = 0;
        int i = 0;
        for (i = 0; i < splitChar.Length; i++)
        {
            index = url.IndexOf(splitChar[i]);
            if (index != -1)
            {
                break;
            }
        }

        if (index == -1)
        {
            id = "0";
        }
        else
        {
            id = url.Substring(index + splitChar[i].Length, url.Length - index - splitChar[i].Length);

            // 进行解密

            try
            {
                SymmetricMethod sm = new SymmetricMethod();

                id = Convert.ToString(sm.Decrypto(id));
            }
            catch
            {
                //Response.Write("<script>alert('解析地址时出错!!');window.location.href='"+tourl+"';</script>");
                return "0";
            }
        }

        return id;
    }
    #endregion

    #region 加密
    public static string IDEncrypto(string id)
    {
        SymmetricMethod sm = new SymmetricMethod();
        string strID = sm.Encrypto(id);

        return strID;

    }
    #endregion

    #region 发送邮件
    /// <summary>
    /// Jmail发邮件
    /// </summary>
    /// <param name="toEmail">接收者（多位用分号隔开）</param>
    /// <param name="toCCMail">抄送（多位用分号隔开）</param>
    /// <param name="toBCCMail">密送（多位用分号隔开）</param>
    /// <param name="FromEmail">发件者</param>
    /// <param name="strToName">收件人姓名</param>
    /// <param name="strFromName">发件人姓名</param>
    /// <param name="strContent">邮件内容</param>
    /// <param name="strTitle">邮件标题</param>
    /// <param name="strContentType">邮件类别（html或者text）</param>
    /// <param name="strFiles">附件（多个用分号隔开）</param>
    /// <returns></returns>
    public static bool SendEmail(string toEmail, string toCCMail, string toBCCMail, string strToName, string strFromName, string strContent, string strTitle, string strContentType, string strFiles)
    {

        jmail.Message Jmail = new jmail.Message();


        int i = 0;
        //toBCCMail = "";
        //toCCMail = "";
        try
        {
            //Silent属性：如果设置为true,JMail不会抛出例外错误. JMail. Send( () 会根据操作结果返回true或false
            Jmail.Silent = true;
            //Jmail创建的日志，前提loging属性设置为true
            Jmail.Logging = true;
            //字符集，缺省为"US-ASCII"
            Jmail.Charset = "GB2312";
            //信件的contentype. 缺省是"text/plain"） : 字符串如果您以HTML格式发送邮件, 改为"text/html"即可。
            //Jmail.ContentType = "Multipart/Mixed";
            //添加收件人
            string[] strArryToMail;
            string[] strArryToCCMail;
            string[] strArryToBCCMail;
            // toEmail = System.Configuration.ConfigurationManager.AppSettings["toEmail"].ToString();
            if (toEmail == "")
            {
                Jmail.Close();
                return false;
            }
            else
            {
                strArryToMail = toEmail.Split(";".ToCharArray());
            }
            for (i = 0; i < strArryToMail.Length; i++)
            {
                Jmail.AddRecipient(strArryToMail[i], "", "");
            }

            //Jmail.add
            //抄送
            toCCMail = "";
            if (toCCMail != "")
            {
                strArryToCCMail = toCCMail.Split(";".ToCharArray());
                for (i = 0; i < strArryToCCMail.Length; i++)
                {
                    Jmail.AddRecipientCC(strArryToCCMail[i], "", "");
                }
            }
            //密送
            toBCCMail = "";
            if (toBCCMail != "")
            {
                strArryToBCCMail = toBCCMail.Split(";".ToCharArray());
                for (i = 0; i < strArryToBCCMail.Length; i++)
                {
                    Jmail.AddRecipientBCC(strArryToBCCMail[i], "");
                }
            }

            Jmail.From = System.Configuration.ConfigurationManager.AppSettings["mailusername"].ToString();
            Jmail.FromName = strFromName;
            if (string.IsNullOrEmpty(strFromName))
            {

                string fromName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["FromName"]);
                Jmail.FromName = fromName;

            }
            //发件人邮件用户名
            Jmail.MailServerUserName = System.Configuration.ConfigurationManager.AppSettings["mailusername"].ToString();
            //发件人邮件密码
            Jmail.MailServerPassWord = System.Configuration.ConfigurationManager.AppSettings["mailpassword"].ToString();
            //设置邮件标题
            Jmail.Subject = strTitle;
            //邮件添加附件,(多附件的话，可以再加一条Jmail.AddAttachment( "c:\\test.jpg",true,null);)就可以搞定了。［注］：加了附件，讲把上面的Jmail.ContentType="text/html";删掉。否则会在邮件里出现乱码。
            string[] strArryFiles;
            if (strFiles != "")
            {
                strArryFiles = strFiles.Split(";".ToCharArray());
                for (i = 0; i < strArryFiles.Length; i++)
                {
                    Jmail.AddAttachment(strArryFiles[i], true, null);
                }
            }
            //邮件内容
            if (strContentType.ToLower() == "text")
            {
                Jmail.Body = strContent;

            }
            else
            {
                Jmail.HTMLBody = strContent;
            }
            //Jmail发送的方法
            if (Jmail.Send(System.Configuration.ConfigurationManager.AppSettings["mailSmtpHost"].ToString(), false))
            {
                //
                Jmail.Close();
                return true;
            }
            else
            {
                //
                Jmail.Close();
                return false;
            }

        }
        catch
        {
            Jmail.Close();
            return false;
        }
    }

    #endregion


    #region  提示信息
    /// <summary>
    /// 提示信息 1 提示信息，2 提示信息并跳转，3 跳转
    /// </summary>
    /// <param name="lbl">label</param>
    /// <param name="type">1 提示信息，2 提示信息并跳转，3 跳转</param>
    /// <param name="info">提示信息</param>
    /// <param name="url">跳转url</param>
    public static void MessageInfo(Label lbl, int type, string info, string url)
    {


        if (type == 1)
        {
            lbl.Text = "<script>alert('" + info + "');</script>";
        }
        if (type == 2)
        {
            lbl.Text = "<script>alert('" + info + "');window.location.href='" + url + "';</script>";

        }
        if (type == 3)
        {
            lbl.Text = "<script>window.location.href='" + url + "';</script>";
        }
    }
    #endregion

    #region 得到ip地址
    //得到IP
    public static string GetClientIP()
    {
        string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(result))
        {
            result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
        if (string.IsNullOrEmpty(result))
        {
            result = HttpContext.Current.Request.UserHostAddress;
        }
        return result;
    }
    #endregion
}
